{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Apply the fine-tuned DistilBERT classifier for nostalgia in party manifestos\n",
    "\n",
    "Note: code ran successfully on 1 September 2023\n",
    "Please contact Stefan Müller and Sven-Oliver Proksch if you have any questions.\n",
    "\n",
    "Make sure the folder `distilbert_nostalgic` is in the same folder as this file\n",
    "To preserve the folder structure of the replication materials, download all files from the Dataverse at once.\n",
    "Alternatively, move `config.json`, `pytorch_model.bin`, and `training_args.bin` into a folder named `distilbert_nostalgic`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "# %pip install transformers\n",
    "# install conda: https://conda.io/projects/conda/en/latest/user-guide/getting-started.html"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load functions and fine-tuned DistilBERT model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "## load relevant functions from transformers library\n",
    "from transformers import AutoTokenizer, TrainingArguments, AutoModelForSequenceClassification, Trainer, pipeline\n",
    "import pandas as pd\n",
    "\n",
    "## load tokenizer\n",
    "tokenizer=AutoTokenizer.from_pretrained('distilbert-base-uncased')\n",
    "\n",
    "## load suggestion_and_solution model\n",
    "model_nostalgic=AutoModelForSequenceClassification.from_pretrained(\n",
    "        \"distilbert_nostalgic\",\n",
    "        num_labels=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Show how to classify sentences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'label': 'LABEL_1', 'score': 0.9253807663917542},\n",
       " {'label': 'LABEL_1', 'score': 0.7654881477355957},\n",
       " {'label': 'LABEL_0', 'score': 0.9970166683197021},\n",
       " {'label': 'LABEL_1', 'score': 0.9948798418045044},\n",
       " {'label': 'LABEL_0', 'score': 0.9971434473991394},\n",
       " {'label': 'LABEL_1', 'score': 0.99162358045578}]"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## example sentences\n",
    "sents=[\"We long for a time when artisans and craftsmen were revered for their skills, when each piece was meticulously handmade with a touch of love and dedication, carrying with it the stories and memories of a bygone era.\",\n",
    "         \"Let's return to our glorious past.\",\n",
    "         \"Not nostalgic.\",\n",
    "         \"We need to revive our cultural heritage.\",\n",
    "         \"We need to improve our infrastructure.\",\n",
    "         \"Immigration is part of our culture.\"]\n",
    "\n",
    "## run classification pipeline\n",
    "classifier=pipeline(\"text-classification\", \n",
    "                      model=model_nostalgic,\n",
    "                      batch_size=64,\n",
    "                      # device=device, if you have a GPU or Apple' mps, specify device here (cuda.0 or mps); default is CPU\n",
    "                      padding='max_length',\n",
    "                      tokenizer=tokenizer)\n",
    "\n",
    "## get sentence predictions\n",
    "classifier(sents)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Apply classifier to sentences stored in data frame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     label     score\n",
      "0  LABEL_1  0.925381\n",
      "1  LABEL_1  0.765488\n",
      "2  LABEL_0  0.997017\n",
      "3  LABEL_1  0.994880\n",
      "4  LABEL_0  0.996864\n",
      "5  LABEL_1  0.991624\n",
      "   sentence_id                                               text    label  \\\n",
      "0            1  We long for a time when artisans and craftsmen...  LABEL_1   \n",
      "1            2                 Let's return to our glorious past.  LABEL_1   \n",
      "2            3                                     Not nostalgic.  LABEL_0   \n",
      "3            4           We need to revive our cultural heritage.  LABEL_1   \n",
      "4            5            \"We need to improve our infrastructure.  LABEL_0   \n",
      "5            6                Immigration is part of our culture.  LABEL_1   \n",
      "\n",
      "      score  \n",
      "0  0.925381  \n",
      "1  0.765488  \n",
      "2  0.997017  \n",
      "3  0.994880  \n",
      "4  0.996864  \n",
      "5  0.991624  \n"
     ]
    }
   ],
   "source": [
    "# load csv file containing sentences (the file nostalgia_sentences_example.csv contains a list of invented sentences)\n",
    "# note: the sentences are stored in the column called \"text\"\n",
    "df=pd.read_csv('nostalgia_sentences_example.csv')\n",
    "\n",
    "# classify sentences through classification pipeline\n",
    "classifier=pipeline(\"text-classification\", \n",
    "                      model=model_nostalgic,\n",
    "                      batch_size=64,\n",
    "                      # device=device, if you have a GPU or Apple' mps, specify device here (cuda.0 or mps); default is CPU\n",
    "                      padding='max_length',\n",
    "                      tokenizer=tokenizer)\n",
    "\n",
    "# get the \"text\" column from \"df\" and store it in a variable called \"text_column\"\n",
    "text_column=df['text'].tolist()\n",
    "\n",
    "# get sentence predictions and store them into a dictionary\n",
    "df_classified=pd.DataFrame(classifier(text_column))\n",
    "\n",
    "# inspect element\n",
    "# label: Label_1=Nostalgic, score=probability of being nostalgic\n",
    "print(df_classified)\n",
    "\n",
    "# bind with original data frame\n",
    "df_combined=pd.concat([df, df_classified], axis=1)\n",
    "\n",
    "# inspect element\n",
    "print(df_combined)\n",
    "\n",
    "# save as csv file\n",
    "df_combined.to_csv('nostalgia_sentences_example_classified.csv', index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pythonProject",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
